package com.qbw.app.module.vehicle;

import androidx.databinding.BindingAdapter;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.widget.ImageView;
import android.widget.TextView;

import com.lib.util.DateTimeUtil;
import com.lib.util.ResUtil;
import com.lib.util.StringUtil;
import com.qbw.app.Constant;
import com.qbw.app.R;
import com.qbw.app.XApplication;
import com.qbw.app.manager.MapManager;
import com.qbw.app.manager.UnitManager;
import com.qbw.app.model.Coolant;
import com.qbw.app.model.Voltage;
import com.qbw.app.module.common.util.Gps;
import com.qbw.app.module.common.util.PositionUtil;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import static com.qbw.app.Constant.VEHICLE_STATUS_DRIVING;
import static com.qbw.app.Constant.VEHICLE_STATUS_FLAMEOUT;
import static com.qbw.app.Constant.VEHICLE_STATUS_ILLEGAL_MOVE;
import static com.qbw.app.Constant.VEHICLE_STATUS_OFFLINE;

/**
 * @author QBW
 * @date 2019/8/29
 */
public class VehicleDataBindingAdapter {

    @BindingAdapter("vehicleTime")
    public static void setVehicleTime(TextView tv, long timestamp) {
        tv.setText(getVehicleTime(timestamp));
    }

    @BindingAdapter("vehicleTimeSecond")
    public static void setVehicleTimeSecond(TextView tv, long timestamp) {
        tv.setText(getVehicleTime(timestamp, true));
    }

    public static String getVehicleTime(long timestamp) {
        return getVehicleTime(timestamp, false);
    }

    public static String getVehicleTime(long timestamp, boolean showSecond) {
        if (timestamp <= 0) {
            return ResUtil.getString(R.string.na);
        }
        int year = DateTimeUtil.getYear(timestamp);
        int currentYear = DateTimeUtil.getYear(DateTimeUtil.getServerCurrentTimeMillis());
        SimpleDateFormat sdf = new SimpleDateFormat(year == currentYear ? (showSecond ? "HH:mm:ss MM/dd" : "HH:mm MM/dd") : (showSecond ? "HH:mm:ss yyyy/MM/dd" : "HH:mm yyyy/MM/dd"),
                                                    Locale.getDefault());
        return sdf.format(new Date(timestamp));
    }

    @BindingAdapter("vehicleLastUpdateTime")
    public static void setVehicleLastUpdateTime(TextView tv, long timestamp) {
        String time = ResUtil.getString(R.string.na);
        if (timestamp > 0) {
            int year = DateTimeUtil.getYear(timestamp);
            int currentYear = DateTimeUtil.getYear(DateTimeUtil.getServerCurrentTimeMillis());
            SimpleDateFormat sdf = new SimpleDateFormat(year == currentYear ? "HH:mm:ss MM/dd" : "HH:mm:ss yyyy/MM/dd",
                                                        Locale.getDefault());
            time = sdf.format(new Date(timestamp));
        }
        tv.setText(String.format(ResUtil.getString(R.string.last_update_time_format), time));
    }

    @BindingAdapter("vehicleVoltageRangeText")
    public static void setVehicleVoltageRangeText(TextView tv, String range) {
        List<Double> doubles = StringUtil.doubles(range, "#");
        if (doubles == null || doubles.size() < 2) {
            tv.setText(R.string.na);
            return;
        }
        tv.setText(new StringBuilder().append(doubles.get(0))
                                      .append("V-")
                                      .append(doubles.get(1))
                                      .append("V"));
    }

    @BindingAdapter("vehicleProblemUpdateTime")
    public static void setVehicleProblemUpdateTime(TextView tv, long timestamp) {
        //setVehicleTime(tv, timestamp);
        setVehicleTimeSecond(tv, timestamp);
    }

    public static void setVehicleProglemHistoryTime(TextView tv, long startTime, long endTime) {
        tv.setText(getVehicleTime(startTime, true) + " - " + getVehicleTime(endTime, true));
    }

    public static void setVehicleLocatinTime(TextView tv, long timestamp) {
        setVehicleTime(tv, timestamp);
    }

    @BindingAdapter("vehicleStateString")
    public static void setVehicleStateString(TextView tv, int state) {
        if (state == VEHICLE_STATUS_DRIVING) {
            tv.setText(R.string.draving_state_driving);
        } else if (state == VEHICLE_STATUS_FLAMEOUT) {
            tv.setText(R.string.draving_state_stalling);
        } else if (state == VEHICLE_STATUS_ILLEGAL_MOVE) {
            tv.setText(R.string.draving_state_illegal_move);
        } else if (state == VEHICLE_STATUS_OFFLINE || state == Constant.VEHICLE_STATUS_INVALID) {
            tv.setText(R.string.draving_state_offline);
        }
    }


    @BindingAdapter("electricAreaStateDrawableLeft")
    public static void setElectricAreaStateDrawableLeft(TextView tv, int state) {
        Drawable[] drawables = tv.getCompoundDrawables();
        tv.setCompoundDrawablesWithIntrinsicBounds(XApplication.getInstance()
                                                               .getResources()
                                                               .getDrawable(
                                                                       getElectricAreaStateDrawable(
                                                                               state)),
                                                   drawables[1],
                                                   drawables[2],
                                                   drawables[3]);
    }

    public static int getElectricAreaStateDrawable(int state) {
        int d = R.drawable.electricarea_enabled;
        if (state == Constant.ELECTRIC_AREA_STATE_CLOSE) {
            d = R.drawable.electricarea_disnabled;
        }
        return d;
    }

    @BindingAdapter("electricAreaModeByState")
    public static void setElectricAreaModeByState(TextView tv, int state) {
        tv.setText(getElectricAreaModeByState(state));
    }

    public static String getElectricAreaModeByState(int state) {
        return ResUtil.getString(state == Constant.ELECTRIC_AREA_MODE_IN ? R.string.mode_in : R.string.mode_out);
    }

    @BindingAdapter("distance")
    public static void setDistance(TextView textView, double km) {
        if (UnitManager.getInstance().isUseKm()) {
            String s = String.format(Locale.getDefault(), "%.1fkm", km);
            SpannableString ss = new SpannableString(s);
            int i = s.indexOf("km");
            AbsoluteSizeSpan sizeSpan = new AbsoluteSizeSpan((int) (textView.getTextSize() / 1.3));
            ss.setSpan(sizeSpan, i, i + 2, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
            textView.setText(ss);
        } else {
            String s = String.format(Locale.getDefault(),
                                     "%.1fmile",
                                     PositionUtil.convertKmToMile(km));
            SpannableString ss = new SpannableString(s);
            int i = s.indexOf("mile");
            AbsoluteSizeSpan sizeSpan = new AbsoluteSizeSpan((int) (textView.getTextSize() / 1.3));
            ss.setSpan(sizeSpan, i, i + 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
            textView.setText(ss);
        }
    }

    @BindingAdapter("distanceInt")
    public static void setDistanceInt(TextView textView, double km) {
        if (UnitManager.getInstance().isUseKm()) {
            String s = String.format(Locale.getDefault(), "%dkm", (int) km);
            SpannableString ss = new SpannableString(s);
            int i = s.indexOf("km");
            AbsoluteSizeSpan sizeSpan = new AbsoluteSizeSpan((int) (textView.getTextSize() / 1.3));
            ss.setSpan(sizeSpan, i, i + 2, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
            textView.setText(ss);
        } else {
            String s = String.format(Locale.getDefault(),
                                     "%dmile",
                                     (int) PositionUtil.convertKmToMile(km));
            SpannableString ss = new SpannableString(s);
            int i = s.indexOf("mile");
            AbsoluteSizeSpan sizeSpan = new AbsoluteSizeSpan((int) (textView.getTextSize() / 1.3));
            ss.setSpan(sizeSpan, i, i + 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
            textView.setText(ss);
        }
    }

    @BindingAdapter("distanceValue")
    public static void setDistanceValue(TextView textView, double km) {
        if (UnitManager.getInstance().isUseKm()) {
            textView.setText(String.valueOf((int) km));
        } else {
            textView.setText(String.valueOf((int) PositionUtil.convertKmToMile(km)));
        }
    }

    @BindingAdapter("speedHour")
    public static void setSpeedHour(TextView textView, double km) {
        if (UnitManager.getInstance().isUseKm()) {
            String s = "--km/h";
            if(km >= 0d) {
                s = String.format(Locale.getDefault(), "%.1fkm/h", km);
            }
            SpannableString ss = new SpannableString(s);
            int i = s.indexOf("km");
            AbsoluteSizeSpan sizeSpan = new AbsoluteSizeSpan((int) (textView.getTextSize() / 1.3));
            ss.setSpan(sizeSpan, i, i + 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
            textView.setText(ss);
        } else {
            String s = "--mi/h";
            if(km >= 0d) {
                s = String.format(Locale.getDefault(),
                        "%.1fmi/h",
                        PositionUtil.convertKmToMile(km));
            }
            SpannableString ss = new SpannableString(s);
            int i = s.indexOf("mi");
            AbsoluteSizeSpan sizeSpan = new AbsoluteSizeSpan((int) (textView.getTextSize() / 1.3));
            ss.setSpan(sizeSpan, i, i + 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
            textView.setText(ss);
        }
    }

    @BindingAdapter("travelCountFormat")
    public static void setTravelCountFormat(TextView textView, int count) {
        String ci = ResUtil.getString(R.string.ci);
        String s = count + ci;
        SpannableString ss = new SpannableString(s);
        int i = s.indexOf(ci);
        AbsoluteSizeSpan sizeSpan = new AbsoluteSizeSpan((int) (textView.getTextSize() / 1.3));
        ss.setSpan(sizeSpan, i, i + ci.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        textView.setText(ss);
    }

    @BindingAdapter("oilUse")
    public static void setOilUse(TextView textView, double oilL) {
        if (UnitManager.getInstance().isUseKm()) {
            String s = String.format(Locale.getDefault(), "%.1fL", oilL);
            SpannableString ss = new SpannableString(s);
            int i = s.indexOf("L");
            AbsoluteSizeSpan sizeSpan = new AbsoluteSizeSpan((int) (textView.getTextSize() / 1.3));
            ss.setSpan(sizeSpan, i, i + 1, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
            textView.setText(ss);
        } else {
            String s = String.format(Locale.getDefault(),
                                     "%.1fgal",
                                     PositionUtil.convertLToGal(oilL));
            SpannableString ss = new SpannableString(s);
            int i = s.indexOf("gal");
            AbsoluteSizeSpan sizeSpan = new AbsoluteSizeSpan((int) (textView.getTextSize() / 1.3));
            ss.setSpan(sizeSpan, i, i + 3, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
            textView.setText(ss);
        }
    }

    @BindingAdapter("oilUseOfHundredKm")
    public static void setOilUseOfHundredKm(TextView textView, double oilL) {
        if (UnitManager.getInstance().isUseKm()) {
            String s = String.format(Locale.getDefault(), "%.1fL/100km", oilL);
            SpannableString ss = new SpannableString(s);
            int i = s.indexOf("L");
            AbsoluteSizeSpan sizeSpan = new AbsoluteSizeSpan((int) (textView.getTextSize() / 1.3));
            ss.setSpan(sizeSpan, i, i + 7, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
            textView.setText(ss);
        } else {
            String s = String.format(Locale.getDefault(),
                                     "%.1fgal/100mi",
                                     PositionUtil.convertLToGal(PositionUtil.convertMileToKm(100) / 100 * oilL));
            SpannableString ss = new SpannableString(s);
            int i = s.indexOf("gal");
            AbsoluteSizeSpan sizeSpan = new AbsoluteSizeSpan((int) (textView.getTextSize() / 1.3));
            ss.setSpan(sizeSpan, i, i + 9, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
            textView.setText(ss);
        }
    }

    @BindingAdapter("temperatureInt")
    public static void setTemperatureInt(TextView textView, String value) {
        textView.setText(String.format(Locale.getDefault(),
                                       ResUtil.getString(R.string.temperature_format),
                                       (int) StringUtil.numberFloat(value)));
    }

    /**
     * 电瓶电压的状态
     */
    @BindingAdapter("voltageStatusText")
    public static void setVoltageStatusText(TextView tv, String state) {
        int sr = R.string.voltage_normal;
        tv.setTextColor(XApplication.getInstance().getResources().getColor(R.color.nm_normal));
        if (Voltage.NORMAL.equals(state)) {
            sr = R.string.voltage_normal;
        } else if (Voltage.SIDE_LOW.equals(state)) {
            sr = R.string.voltage_lower;
            tv.setTextColor(XApplication.getInstance().getResources().getColor(R.color.nm_side_low));
        } else if (Voltage.EXCEPTION.equals(state)) {
            sr = R.string.high_temperature;
            tv.setTextColor(XApplication.getInstance().getResources().getColor(R.color.nm_exception));
        } else if (Voltage.NO_DATA.equals(state)) {
            sr = R.string.na;
        } else if (Voltage.SIDE_HIGH.equals(state)) {
//            sr = R.string.voltage_hight;
            sr = R.string.exception;
        } else if (Voltage.LOW.equals(state)) {
//            sr = R.string.voltage_lower_electric;
            sr = R.string.exception;
            tv.setTextColor(XApplication.getInstance().getResources().getColor(R.color.nm_exception));
        }
        tv.setText(sr);
    }

    /**
     * 电瓶电压的状态  电瓶电压状态，1：正常，0--（无数据） -1 异常 2 偏低 3 偏高 4 低电
     */
    @BindingAdapter("voltageStatusText")
    public static void setVoltageDetailStatusText(TextView tv, String state) {
        int sr = R.string.voltage_normal;
        tv.setTextColor(XApplication.getInstance().getResources().getColor(R.color.nm_normal));
        if (Voltage.NORMAL.equals(state)) {
            sr = R.string.voltage_normal;
        } else if (Voltage.SIDE_LOW.equals(state)) {
            sr = R.string.voltage_lower;
        } else if (Voltage.EXCEPTION.equals(state)) {
            sr = R.string.high_temperature;
        } else if (Voltage.NO_DATA.equals(state)) {
            sr = R.string.na;
        } else if (Voltage.SIDE_HIGH.equals(state)) {
            sr = R.string.voltage_hight;
            sr = R.string.exception;
        } else if (Voltage.LOW.equals(state)) {
//            sr = R.string.voltage_lower_electric;
            sr = R.string.voltage_lower_electric;
        }
        tv.setText(sr);
    }


    /**
     * 电瓶电压的状态
     */
    @BindingAdapter("voltageStatusDrawable")
    public static void setVoltageStatusDrawable(ImageView iv, String state) {
        int dr = R.drawable.nm_icon_vol_normal;
        if (Voltage.NORMAL.equals(state)) {
            dr = R.drawable.nm_icon_vol_normal;
        } else if (Voltage.SIDE_LOW.equals(state)) {
            dr = R.drawable.nm_icon_vol_yellow;
        } else if (Voltage.EXCEPTION.equals(state)) {
            dr = R.drawable.nm_icon_vol_normal;
        } else if (Voltage.NO_DATA.equals(state)) {
            dr = R.drawable.nm_icon_vol_not_normal;
        } else if (Voltage.SIDE_HIGH.equals(state)) {
            dr = R.drawable.nm_icon_vol_normal;
        } else if (Voltage.LOW.equals(state)) {
            dr = R.drawable.nm_icon_vol_red;
        }
        iv.setImageResource(dr);
    }

    @BindingAdapter("coolantStatusText")
    public static void setCoolantStatusText(TextView tv, String state) {
        int sr = R.string.voltage_normal;
        tv.setTextColor(XApplication.getInstance().getResources().getColor(R.color.nm_normal));
        if (Coolant.NORMAL.equals(state)) {
            sr = R.string.voltage_normal;
        } else if (Coolant.NO_DATA.equals(state)) {
            sr = R.string.na;
        } else if (Coolant.EXCEPTION.equals(state)) {
            sr = R.string.exception;
            tv.setTextColor(XApplication.getInstance().getResources().getColor(R.color.nm_exception));
        }
        tv.setText(sr);
    }

    @BindingAdapter("coolantStatusDrawable")
    public static void setCoolantStatusDrawable(ImageView iv, String state) {
        int dr = R.drawable.nm_icon_temp_normal;
        if (Coolant.NORMAL.equals(state)) {
            dr = R.drawable.nm_icon_temp_normal;
        } else if (Coolant.NO_DATA.equals(state)) {
            dr = R.drawable.nm_icon_not_normal;
        } else if (Coolant.EXCEPTION.equals(state)) {
            dr = R.drawable.nm_icon_temp_red;
        }
        iv.setImageResource(dr);
    }

    public static void setFaultStatusDrawable(ImageView iv, String state, int faultCount) {
        int dr = R.drawable.nm_icon_problem_normal;
        if (faultCount > 0) {
            dr = R.drawable.nm_icon_problem_red;
        }
        iv.setImageResource(dr);
    }

    @BindingAdapter("dateYearMonthDay")
    public static void setDateYearMonthDay(TextView textView, long timestamp) {
        String date;
        if (timestamp <= 0) {
            date = ResUtil.getString(R.string.na);
        }
        int year = DateTimeUtil.getYear(timestamp);
        int currentYear = DateTimeUtil.getYear(DateTimeUtil.getServerCurrentTimeMillis());
        SimpleDateFormat sdf = new SimpleDateFormat(year == currentYear ? "MM/dd" : "yyyy/MM/dd",
                                                    Locale.getDefault());
        date = sdf.format(new Date(timestamp));
        textView.setText(date);
    }

    public static int getTravelLocationEndDrawable(int drivingState) {
        int d = R.drawable.travel_driving;
        if (drivingState == Constant.VEHICLE_STATUS_DRIVING) {
            d = R.drawable.travel_driving;
        } else if (drivingState == Constant.VEHICLE_STATUS_OFFLINE) {
            d = R.drawable.travel_offline;
        } else if (drivingState == Constant.VEHICLE_STATUS_FLAMEOUT) {
            d = R.drawable.travel_flameout;
        } else if (drivingState == Constant.VEHICLE_STATUS_ILLEGAL_MOVE) {
            d = R.drawable.travel_wrong_move;
        }
        return d;
    }

    public static int getTravelLocationEndDrawable1(int drivingState) {
        int d = R.drawable.nm_icon_car_offline;
        if (drivingState == Constant.VEHICLE_STATUS_DRIVING) {
            d = R.drawable.nm_icon_car_driving;
        } else if (drivingState == Constant.VEHICLE_STATUS_OFFLINE) {
            d = R.drawable.nm_icon_car_offline;
        } else if (drivingState == Constant.VEHICLE_STATUS_FLAMEOUT) {
            d = R.drawable.nm_icon_car_power_off;
//        } else if (drivingState == Constant.VEHICLE_STATUS_ILLEGAL_MOVE) {
//            d = R.drawable.mbike_illeagle_move;
        }
        return d;
    }

    @BindingAdapter("percentFormat")
    public static void setPercentFormat(TextView textView, String value) {
        int f = (int) StringUtil.numberFloat(value);
        textView.setText(String.format(ResUtil.getString(R.string.percent_format), f));
    }

    public static void setWarningUnreadMany(TextView textView, int count) {
        String format = ResUtil.getString(R.string.warning_unread_message_format);
        String s = String.format(format, count);
        SpannableString ss = new SpannableString(s);
        String sc = String.valueOf(count);
        int i = s.indexOf(sc);
        ForegroundColorSpan colorSpan = new ForegroundColorSpan(Color.parseColor("#E82747"));
        ss.setSpan(colorSpan, i, i + sc.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        textView.setText(ss);
    }


    @BindingAdapter("alarmIdImageFlag")
    public static void setAlarmIdImageFlag(ImageView imageView, long alarmId) {
        imageView.setImageResource(getAlarmIdImageFlag(alarmId, R.drawable.vehicle_warning));
    }

    public static int getAlarmIdImageFlag(long alarmId, int defaultResId) {
        int rid = defaultResId;
        if (alarmId == Constant.EVENT_SHOCK_AFTER_STALLING) {
            rid = R.drawable.xihuo_zhendong;
        } else if (alarmId == Constant.EVENT_POSSIBLE_CRASH) {
            rid = R.drawable.yisi_pengzhuang;
        } else if (alarmId == Constant.EVENT_POSSIBLE_ROLLOVER) {
            rid = R.drawable.yisi_fanche;
        } else if (alarmId == Constant.EVENT_DEVICE_OUT) {
            rid = R.drawable.shebei_bachu;
        } else if (alarmId == Constant.EVENT_ILLEGAL_MOVE) {
            rid = R.drawable.feifa_weiyi;
        } else if (alarmId == Constant.EVENT_ELEC_AREA_IN) {
            rid = R.drawable.dianzi_shiru;
        } else if (alarmId == Constant.EVENT_ELEC_AREA_OUT) {
            rid = R.drawable.dianzi_shichu;
        } else if (alarmId == Constant.EVENT_INCREASE_SPEED) {
            rid = R.drawable.ji_jiasu;
        } else if (alarmId == Constant.EVENT_REDUCE_SPEED) {
            rid = R.drawable.ji_jiansu;
        } else if (alarmId == Constant.EVENT_TURN_HURRY) {
            rid = R.drawable.ji_zhuanwan;
        } else if (alarmId == Constant.EVENT_LOWER_ELE) {
            rid = R.drawable.dianping_diya;
        }
        return rid;
    }

    public static int getAlarmIdImage(long alarmId, int defaultResId) {
        int rid = defaultResId;
        if (alarmId == Constant.EVENT_SHOCK_AFTER_STALLING) {
            rid = R.drawable.shark_after_flameout;
        } else if (alarmId == Constant.EVENT_POSSIBLE_CRASH) {
            rid = R.drawable.possible_crash;
        } else if (alarmId == Constant.EVENT_POSSIBLE_ROLLOVER) {
            rid = R.drawable.possible_rollover;
        } else if (alarmId == Constant.EVENT_DEVICE_OUT) {
            rid = R.drawable.device_out;
        } else if (alarmId == Constant.EVENT_ILLEGAL_MOVE) {
            rid = R.drawable.illegal_move;
        } else if (alarmId == Constant.EVENT_ELEC_AREA_IN) {
            rid = R.drawable.drive_in_electric;
        } else if (alarmId == Constant.EVENT_ELEC_AREA_OUT) {
            rid = R.drawable.drive_out_electric;
        } else if (alarmId == Constant.EVENT_INCREASE_SPEED) {
            rid = R.drawable.ji_add;
        } else if (alarmId == Constant.EVENT_REDUCE_SPEED) {
            rid = R.drawable.ji_minus;
        } else if (alarmId == Constant.EVENT_TURN_HURRY) {
            rid = R.drawable.ji_turn;
        } else if (alarmId == Constant.EVENT_LOWER_ELE) {
            rid = R.drawable.lower_power;
        }
        return rid;
    }

    public static Gps convertGpsToCurrentMapGps(double lat, double lng) {
        Gps gps;
        if (MapManager.getInstance().isUseBaidu()) {
            gps = PositionUtil.gps84_to_bd09_byBaiduSdk(lat, lng);
        } else {
            gps = PositionUtil.gps84_To_Gcj02(lat, lng);
        }
        return gps;
    }

    @BindingAdapter({"vehicleName", "vehicleDrivingState"})
    public static void setVehicleNameByState(TextView tv, String name, int state) {
        tv.setText(name + (state == Constant.VEHICLE_STATUS_OFFLINE ? (String.format(Locale.getDefault(),
                                                                                     "(%s)",
                                                                                     ResUtil.getString(
                                                                                             R.string.offline))) : ""));
    }
}
